#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vi: ts=4 expandtab
#
# Copyright (C) 2014
#
# Author: Choonho Son <choonho.son@gmail.com>
#

import netsnmp
import gviz_api

community = 'public'
version = 2

description = {"name": ("string", "Name"),
               "desc": ("string", "Description")}

MIB = {
    'sysDescr'    : '.1.3.6.1.2.1.1.1.0',
    'sysObjectID' : '.1.3.6.1.2.1.1.2.0',
    'sysUpTime'   : '.1.3.6.1.2.1.1.3.0', 
    'sysContact'  : '.1.3.6.1.2.1.1.4.0',
    'sysName'     : '.1.3.6.1.2.1.1.5.0',
    'sysLocation' : '.1.3.6.1.2.1.1.6.0',
    'sysServices' : '.1.3.6.1.2.1.1.7.0',
}


def get_system(host,community='public', version=2):

    s = netsnmp.Session(DestHost=host, Version=version, Community=community)

    result = {}
    for oid in MIB.keys():
        vars = netsnmp.VarList(netsnmp.Varbind(MIB[oid]))
        value = s.get(vars)
        result[oid] = value[0]


    return result


def index(req):
    req.add_common_vars()
    env_vars = req.subprocess_env
    getReqStr = env_vars['QUERY_STRING']
    getReqArr = getReqStr.split('&')   
    getReqDict = {}

    for item in getReqArr:   
        tempArr = item.split('=') 
        getReqDict[tempArr[0]] = tempArr[1]

    # Parse parameter for snmp connection (community, version) 
    if getReqDict.has_key('community'):
        community = getReqDict['community']
    if getReqDict.has_key('version'):
        version = int(getReqDict['version'])
 
    req.content_type = 'text/javascript'
    
    status = '200 OK'

    data = []
    result = get_system(getReqDict['host'], community, version)
    for item in result.keys():
        index = {"name": item, "desc": result['item']}
        data.append(index)


    data_table = gviz_api.DataTable(description)
    data_table.LoadData(data)


    output = data_table.ToJSonResponse(columns_order=("Label", "Value"),
                                order_by="Label")


    return output

if __name__ == "__main__":
    host = raw_input("host IP> ")
    print get_system(host)
